package com.ssy.jt808.gateway.infrastructure.config;

import com.ssy.jt808.gateway.application.endpoint.JTHandlerInterceptor;
import com.ssy.jt808.gateway.application.endpoint.JTMultiPacketListener;
import com.ssy.jt808.gateway.application.endpoint.JTSessionListener;
import com.ssy.jt808.gateway.application.service.TerminalAppService;
import com.ssy.jt808.gateway.infrastructure.enums.SessionAttribute;
import com.ssy.jt808.protocol.codec.DataFrameMessageDecoder;
import com.ssy.jt808.protocol.codec.JTMessageAdapter;
import com.ssy.jt808.protocol.codec.JTMessageEncoder;
import com.ssy.jt808.protocol.codec.MultiPacketDecoder;
import com.ssy.netmc.core.HandlerMapping;
import com.ssy.netmc.core.SpringHandlerMapping;
import com.ssy.netmc.session.SessionListener;
import com.ssy.netmc.session.SessionManager;
import io.github.yezhihao.protostar.SchemaManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JtBeanConfig{

    @Bean
    public HandlerMapping handlerMapping() {
        return new SpringHandlerMapping();
    }

    @Bean
    public JTHandlerInterceptor handlerInterceptor() {
        return new JTHandlerInterceptor();
    }

    @Bean
    public SessionListener sessionListener( TerminalAppService terminalStatusService ){
        return new JTSessionListener(terminalStatusService);
    }

    @Bean
    public SessionManager sessionManager(SessionListener sessionListener) {
        return new SessionManager(SessionAttribute.class, sessionListener);
    }

    @Bean
    public SchemaManager schemaManager() {
      return new SchemaManager("com.ssy.jt808.protocol", "com.ssy.jt808.gateway.domain.protocol");
    }

    @Bean
    public JTMessageAdapter messageAdapter(SchemaManager schemaManager) {
        JTMessageEncoder encoder = new JTMessageEncoder(schemaManager);
        MultiPacketDecoder decoder = new MultiPacketDecoder(schemaManager, new JTMultiPacketListener(10));
        return new WebLogAdapter(encoder, decoder);
    }

    @Bean
    public JTMessageAdapter alarmFileMessageAdapter(SchemaManager schemaManager) {
        JTMessageEncoder encoder = new JTMessageEncoder(schemaManager);
        DataFrameMessageDecoder decoder = new DataFrameMessageDecoder(schemaManager, new byte[]{0x30, 0x31, 0x63, 0x64});
        return new WebLogAdapter(encoder, decoder);
    }

    @Bean
    public MultiPacketDecoder multiPacketDecoder(SchemaManager schemaManager) {
        return new MultiPacketDecoder(schemaManager);
    }
}